package com.sein.foods;

import java.util.ArrayList;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;

public class SQLHandler extends SQLiteOpenHelper {
	public Context context;
	public static String DATABASE_NAME = "kawe.db";
	public static int DATABASE_VERSION = 1;
	public SQLiteDatabase database;
	public long lastInsertId;
	public static String TABLE_NAME = "performance";
	public static final String INSERT = "insert into " + TABLE_NAME
			+ " (name, number, skypeId, address) values" + "(?,?,?,?)";

	public SQLHandler(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
		this.context = context;
		database = this.getWritableDatabase();
	}

	public void initDB(SQLiteDatabase db) {
		db.execSQL("CREATE TABLE "
				+ TABLE_NAME
				+ " (id INTEGER PRIMARY KEY, name TEXT, number TEXT, skypeId TEXT, address TEXT)");
	}

	public void closeDB() {
		if (database != null) {
			database.close();
		}
	}

	public long insert(String insertStmt, String[] args) {
		SQLiteStatement insertStatement = database.compileStatement(insertStmt);
		for (int i = 0; i < args.length; i++) {
			insertStatement.bindString(i + 1, args[i]);
		}
		this.lastInsertId = insertStatement.executeInsert();
		return this.lastInsertId;
	}

	public long getInsertId() {
		return this.lastInsertId;
	}

	public Cursor _select_(String selectStmt, String[] args) {
		Cursor cursor = database.rawQuery(selectStmt, args);
		return cursor;
	}

	public ArrayList<String[]> select(String selectStmt, String[] args) {
		Cursor cursor = database.rawQuery(selectStmt, args);
		ArrayList<String[]> resultList = new ArrayList<String[]>();
		String[] columnNames = cursor.getColumnNames();
		resultList.add(columnNames);
		if (cursor.moveToFirst()) {
			do {
				String row[] = new String[columnNames.length];
				for (int i = 0; i < row.length; i++) {
					row[i] = cursor.getString(i);
				}
				resultList.add(row);
			} while (cursor.moveToNext());
		}
		if (cursor != null) {
			cursor.close();
		}
		return resultList;
	}
	

	public void executeQuery(String query, String[] args) {
		database.execSQL(query, args);
	}

	public void executeQuery(String query) {
		database.execSQL(query);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		initDB(db);
		System.out.println("Table " + TABLE_NAME + " created");
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
		db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
		onCreate(db);
	}

}
